package cn.edu.sjtu.permission;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.edu.sjtu.DedexerPlus;

public class APIPermissionChecker extends PermissionChecker {

	public APIPermissionChecker(String path) {
		super(path);
	}
	
	public void analyse(HashSet<String> pset, String func, String regValue) {
		String f = null;
		if (regValue != null) {	//reflection
			f = regValue.split(":")[1];
		} else {
			f = func;
		}
		if (pMap.containsKey(f)) {
			setPermissionSet(pset, pMap.get(f));
			System.out.println("App require permission: " + f + " " + pMap.get(f));
		}
		int li = f.lastIndexOf(".");
		String className = f.substring(0, li);
		if (DedexerPlus.extendMap.containsKey(className)) {
			String newFunc = DedexerPlus.extendMap.get(className).toString() + f.substring(li);
			
			if (pMap.containsKey(newFunc)) {
				setPermissionSet(pset, pMap.get(newFunc));
				System.out.println("App require permission: " + newFunc + " " + pMap.get(newFunc));
			}
		}
	}
	
    protected void setPermissionMap(String path, HashMap<String, String> map) {
    	try {
			XSSFWorkbook xwb = new XSSFWorkbook(path);
			XSSFSheet sheet = xwb.getSheetAt(0);
			XSSFRow row;
			for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
				row = sheet.getRow(i);
				if (row != null && row.getCell(0) != null
						&& !row.getCell(0).equals("")) {
					if (row.getCell(2) != null && row.getCell(2).toString().contains("android")) {
						map.put(row.getCell(0).toString().split("[(]")[0], row.getCell(1).toString() + "&" + row.getCell(2).toString());
						//System.out.println(row.getCell(0).toString().split("[(]")[0] + " " + row.getCell(1).toString() + "&" + row.getCell(2).toString());
					}
					else {
						map.put(row.getCell(0).toString().split("[(]")[0], row.getCell(1).toString());
						//System.out.println(row.getCell(0).toString().split("[(]")[0] + " " + row.getCell(1).toString());
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void checkPermission(DedexerPlus ddxp) {
		if (cSet.size() > 0) {
			Iterator it = cSet.iterator();
        	while (it.hasNext()) {
        		String s = ((String )it.next());
        		if (s.contains("@")) {
            		String[] sa = s.split("@");
            		ddxp.getRegValueToCheck(sa[0], Long.parseLong(sa[1]), Integer.parseInt(sa[2]), sa[3], sa[4], 0, this);
        		}
        	}
		}
	}
}
